package com.tos.second.task;

import com.tos.second.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String expiredKey = new String(message.getBody());

        // 判断是否为订单过期键
        if (expiredKey.startsWith("order:timeout:")) {
            String orderNumber = expiredKey.replace("order:timeout:", "");
            try {
                // 删除过期的未支付订单
                int deletedCount = ordersMapper.deleteUnpaidOrderByNumber(orderNumber);
                if (deletedCount > 0) {
                    log.info("订单 {} 已过期并自动删除", orderNumber);
                    // 清理相关缓存
                    deleteRedisCaches();
                }
            } catch (Exception e) {
                log.error("处理过期订单 {} 时发生错误", orderNumber, e);
            }
        }
    }

    private void deleteRedisCaches() {
        // 清理缓存逻辑
        List<String> aKeys = Arrays.asList(
                "newGoodsCache",
                "goodsCache",
                "user_goods",
                "home",
                "category_goods",
                "recGoods"
        );

        for (String key : aKeys) {
            Set<String> keys = redisTemplate.keys(key + ":*");
            if (keys != null && !keys.isEmpty()) {
                redisTemplate.delete(keys);
                log.info("删除key成功");
            }
        }
    }
}
